package com.pine.dbant.plugin.sqlite.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.JdbcMetadataTreeView;
import com.pine.dbant.common.plugin.meta.*;
import com.pine.sunflower.core.utils.Strings;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SqliteCatalogFunction extends AbstractQueryMetadataFunction<JdbcMetadataAnalysisConfig, List> {

    public SqliteCatalogFunction(String type) {
        super(type);
    }

    @Override
    public List<MetadataNode> doQuery(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        List<MetadataNode> metadataNodes = new ArrayList<>();
        String allCatalogSql = "PRAGMA database_list";
        List<Map<String, Object>>  catalogResult = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(allCatalogSql);
        catalogResult.forEach(map->{
            String name = String.valueOf(map.get("name"));
            metadataNodes.add(new DefaultMetadataNode()
                    .setName(name)
                    .setId(Strings.format("{}_{}", metadataAnalysisConfig.getConnectionInfo().getId(), name))
                    .setType(JdbcMetadataTreeView.CATALOG.getType())
//                        .setParentId(String.valueOf(metadataAnalysisConfig.getConnectionInfo().getId()))
                    .addProperty(CONN_ID, metadataAnalysisConfig.getConnectionInfo().getId())
                    .addProperty(CATALOG, name));
        });
        return metadataNodes;
    }
}
